package com.yingpai.fitness.dvp_2_0.main.activity.fitness;

import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.common.view.statusbar.Status;
import com.yingpai.fitness.dvp_2_0.main.bean.StepDetailBean;
import com.yingpai.fitness.dvp_2_0.main.util.CountDownTimer;
import com.yingpai.fitness.dvp_2_0.main.util.Util;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.entity.UpdateStepBean;
import com.zzhoujay.richtext.RichText;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 计步规则页面
 */
public class StepDetailActivity extends CommonActivity {

    @BindView(R.id.webtext)
    TextView webtext;
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.todaystep)
    TextView todaystep;
    @BindView(R.id.profit)
    TextView ponit;
    @BindView(R.id.consume)
    TextView calorie;

    private CountDownTimer timer;
    private SensorEventListener sensorEventListener;
    private long stepNum = 0l;
    private boolean isFirst = true;
    private boolean isFirstToast = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusFlag(Contacts.NORMAL_STATUS);
        setContentView(R.layout.dvp_2_0_activity_stepdetail);

        Status.with(this)
                .statusBarBackground(ContextCompat.getColor(this, R.color.colorNavigation))
                .navigationBarBackground(ContextCompat.getDrawable(this, R.color.colorNavigation));

        sensorEventListener = new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent event) {
                Logger.e("步数：" + event.values[0] + "==" + event.timestamp);
                stepNum = (long) event.values[0];
                if(isFirst){
                    postData(stepNum);
                    isFirst = false;
                }
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {
                Logger.e(sensor.getName() + "==" + accuracy);
            }
        };
        if(context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_SENSOR_STEP_COUNTER)){ //
            SensorManager sensorManager= (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
            Sensor stepCounter = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
            sensorManager.registerListener(sensorEventListener, stepCounter, SensorManager.SENSOR_DELAY_FASTEST);
        }

        timer = new CountDownTimer(10000,1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                this.start();
                postData(stepNum);
            }
        }.start();
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if(null != timer)
            timer.start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(null != timer)
            timer.cancel();
    }

    @Override
    @OnClick({R.id.back})
    public void onViewClicked(View view){
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.back:

                finishActivity();
                break;
        }
    }

    @Override
    protected void initData() {
        showDialog(this,"");
        requestNet();
    }

    private void requestNet() {
        finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.GETSTEPCOUNTHOME,
                null, Url.GETSTEPCOUNTHOME, new Callback<StepDetailBean>() {
                    @Override
                    public void onSuccess(StepDetailBean bean) {
                        dismissDialog();
                        if(bean.getCode().equals("0")){
                            RichText.fromHtml(bean.getData().getTepCountRule()).into(webtext);
                            todaystep.setText(bean.getData().getStepCount()+"");
                            ponit.setText(bean.getData().getPonit()+"");
                            calorie.setText(bean.getData().getCalorie()+"");
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDialog();
                    }
                });
    }

    /**
     * 上传步数
     * @param value 步数
     */
    private void postData(long value){
        HashMap<String,Object> map = new HashMap<>();
        map.put("stepCount",(long)value);
        map.put("type","1");
        map.put("phoneCode",Util.getUniquePsuedoID());
        finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.SAVESTEPCOUNT,
                map, Url.SAVESTEPCOUNT, new Callback<UpdateStepBean>() {
                    @Override
                    public void onSuccess(UpdateStepBean bean) {
                        if(bean.getCode().equals("0")){
                            todaystep.setText(bean.getData().getStepCount()+"");
                            ponit.setText(bean.getData().getPonit()+"");
                            calorie.setText(bean.getData().getCalorie()+"");
                        }else{
                            if(isFirstToast){
                                showToast(bean.getMessage());
                                isFirstToast = false;
                            }
                        }
                    }

                    @Override
                    public void onError(Response response) {
                        super.onError(response);
                    }
                });
    }
}